
// CheckIPAddressDlg.cpp : implementation file
//

#include "stdafx.h"
#include "CheckIPAddress.h"
#include "CheckIPAddressDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define STATE_START		1
#define STATE_END		2
#define STATE_AUTOSTART	3

#define MYWM_NOTIFYICON WM_USER+5

enum TimerID
{
	Start,
	AutoStart,
	RunTime,
};

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CCheckIPAddressDlg dialog



CCheckIPAddressDlg::CCheckIPAddressDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CCheckIPAddressDlg::IDD, pParent)
	, m_strPath(_T("D:\\OnlineDisk\\"))
	, m_unInterval(1)
	, m_nIsStart(2)
	, m_unHour(0)
	, m_unMinute(0)
	, m_unSecond(0)
	, m_nAutorunTime(0)
	, m_bNotShowNoChangeMessage(false)
	, m_strIP(TEXT("127.0.0.1"))
	, m_bSingleFile(FALSE)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCheckIPAddressDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST, m_strList);
	DDX_Text(pDX, IDC_EDIT_PATH, m_strPath);
	DDX_Text(pDX, IDC_EDIT_INTERVAL, m_unInterval);
	DDV_MinMaxUInt(pDX, m_unInterval, 1, 60);
	DDX_Control(pDX, IDC_CHECK_AUTORUN, m_CheckBtn);
	DDX_Check(pDX, IDC_CHECK_SINGLEFILE, m_bSingleFile);
}

BEGIN_MESSAGE_MAP(CCheckIPAddressDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDSTART, &CCheckIPAddressDlg::OnBnClickedStart)
	ON_BN_CLICKED(IDEND, &CCheckIPAddressDlg::OnBnClickedEnd)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_SELECT, &CCheckIPAddressDlg::OnBnClickedButtonSelect)
	ON_BN_CLICKED(IDC_CHECK_AUTORUN, &CCheckIPAddressDlg::OnBnClickedCheckAutorun)
	ON_BN_CLICKED(IDC_CHECK_NOCHANGEMSG, &CCheckIPAddressDlg::OnBnClickedCheckNochangemsg)
	ON_BN_CLICKED(IDC_BUTTON_CHECKNOW, &CCheckIPAddressDlg::OnBnClickedButtonChecknow)
	ON_BN_CLICKED(IDC_CHECK_SINGLEFILE, &CCheckIPAddressDlg::OnBnClickedCheckSinglefile)
	ON_MESSAGE(MYWM_NOTIFYICON,OnNotifyIcon)
	ON_COMMAND(ID_NOTIFY_SHOW, &CCheckIPAddressDlg::OnNotifyShow)
	ON_COMMAND(ID_Notify_RUN, &CCheckIPAddressDlg::OnNotifyRun)
	ON_COMMAND(ID_NOTIFY_EXIT, &CCheckIPAddressDlg::OnNotifyExit)
END_MESSAGE_MAP()


// CCheckIPAddressDlg message handlers

BOOL CCheckIPAddressDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	// Fix the window.
	DWORD dwWndLoog = GetWindowLong( m_hWnd, GWL_STYLE );
	dwWndLoog &= ~WS_MAXIMIZEBOX;
	dwWndLoog &= ~WS_THICKFRAME;
	SetWindowLong( m_hWnd, GWL_STYLE, dwWndLoog );

	if( 1 == theApp.GetProfileInt(TEXT("CheckIPAddress"),TEXT("NotShowChangeMessage"),0))
	{ 
		m_bNotShowNoChangeMessage = true;
		CButton* btn = (CButton*)GetDlgItem(IDC_CHECK_NOCHANGEMSG);
		btn->SetCheck(BST_CHECKED);
	}
	if( 1 == theApp.GetProfileInt(TEXT("CheckIPAddress"),TEXT("SingleFile"),0))
	{ 
		m_bSingleFile = true;
		CButton* btn = (CButton*)GetDlgItem(IDC_CHECK_SINGLEFILE);
		btn->SetCheck(BST_CHECKED);
	}

	// Query the "Auto run when start windows" value from registry.
	HKEY hKey = NULL;
	RegOpenKey( HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), &hKey );
	DWORD dwType = REG_SZ;
	DWORD dwSize = MAX_PATH;
	TCHAR data[MAX_PATH] = {0};

	// Query success is Auto run. else don't run.
	if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("CheckIPAddress"), NULL, &dwType,(LPBYTE)&data, &dwSize) )
	{
		m_CheckBtn.SetCheck( BST_CHECKED );
	}

	// Set Check timer.
	SetTimer( TimerID::AutoStart, 1000, NULL );
	SetNotifyIcon( emNotifyIcon::Create );
	UpdateIPAddress();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CCheckIPAddressDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else if ( SC_MINIMIZE == nID  )
	{
		OnNotifyIcon( nID, WM_LBUTTONDOWN );
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CCheckIPAddressDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CCheckIPAddressDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CCheckIPAddressDlg::UpdateIPAddress()
{
	CInternetSession sess(TEXT(""));
	CHttpFile* file = NULL;
	file = (CHttpFile*)sess.OpenURL( TEXT("http://iframe.ip138.com/ic.asp"));
	CString str(TEXT(""));
	CString tmp(TEXT(""));
	while ( TRUE )
	{
		if ( NULL == file->ReadString(tmp) )
		{
			break;
		}
		file->ReadString(str);
	}
	int left = str.Find(TEXT("["));
	int right = str.Find(TEXT("]"));
	str = str.Left(right);
	str = str.Right( right - left -1 );
	if ( STATE_END != m_nIsStart )
	{
		if( 0 != _tcscmp( m_strIP, str ) )
		{
			CString temp;
			temp.Format( TEXT("IP is changed! %s to %s.") ,m_strIP,str);
			m_strList.InsertString(0,temp);
		}
		else
		{
			if ( false == m_bNotShowNoChangeMessage )
			{
				m_strList.InsertString(0, TEXT("IP is no changed.") );
			}
		}
	}

	CFile oFile;

	// Check the path is not exist.
	if( 0 != _taccess_s( m_strPath, 00 ) )
	{
		CreateDirectory( m_strPath, NULL );
	}

	if ( TRUE == m_bSingleFile )
	{
		// Check result is in IPList.txt file.
		m_strIP = str;
		CString strPath(TEXT(""));
		strPath = m_strPath;
		strPath += TEXT("IPList.txt");
		SetDlgItemText( IDC_STATIC_IP, m_strIP );

		if( FALSE == oFile.Open( strPath, CFile::OpenFlags::modeReadWrite | CFile::OpenFlags::modeNoTruncate | CFile::modeCreate ) )
		{
			if ( STATE_END != m_nIsStart )
			{
				m_strList.InsertString( 0,TEXT("Create file error, please check the path is not exist."));
			}
		}
		CString strBuf;
		strBuf = m_strIP;
		strBuf += TEXT("\n");
		oFile.SeekToEnd();
		oFile.Write( strBuf.GetBuffer(strBuf.GetLength()), strBuf.GetLength() );
		oFile.Flush();
	}
	else
	{
		// Check result is ***.***.***.***.txt, one IP is one file.
		m_strIP = str;
		str += TEXT(".txt");
		CString strPath(TEXT(""));
		strPath = m_strPath;
		strPath += str;
		
		SetDlgItemText( IDC_STATIC_IP, m_strIP );
		
		if( FALSE == oFile.Open( strPath, CFile::OpenFlags::modeRead | CFile::OpenFlags::modeCreate ) )
		{
			if ( STATE_END != m_nIsStart )
			{
				m_strList.InsertString( 0,TEXT("Create file error, please check the path is not exist."));
			}
		}
	}
	
	oFile.Close();
	file->Close();
	delete file;
	file = NULL;
	sess.Close();
}

void CCheckIPAddressDlg::OnBnClickedStart()
{
	// TODO: Add your control notification handler code here

	if ( STATE_END == m_nIsStart )
	{
		m_nIsStart = STATE_START;
		CString str;
		str.Format( TEXT("Start check IP address, Check Interval is %d minute, now IP is :"),m_unInterval);
		str += m_strIP;
		m_strList.InsertString(0, str );
		UpdateData(TRUE);
		SetTimer( TimerID::Start, m_unInterval*60*1000, NULL );
		UpdateIPAddress();
		KillTimer( TimerID::AutoStart );
		SetDlgItemText(IDC_STATIC_AUTOSTART,TEXT(""));
	}
}


void CCheckIPAddressDlg::OnBnClickedEnd()
{
	// TODO: Add your control notification handler code here
	
	if ( STATE_END != m_nIsStart )
	{
		m_strList.InsertString(0,TEXT("Check IP address End."));
		KillTimer( TimerID::Start );
		KillTimer( TimerID::AutoStart );
		m_nIsStart = STATE_END;
		KillTimer( TimerID::RunTime );
		SetDlgItemText(IDC_STATIC_AUTOSTART,TEXT(""));
	}
}


void CCheckIPAddressDlg::OnTimer( UINT_PTR nIDEvent )
{
	// TODO: Add your message handler code here and/or call default
	switch ( nIDEvent )
	{
	case TimerID::Start:
		{
			UpdateIPAddress();
		}
		break;
	case TimerID::AutoStart:
		{
			m_nAutorunTime++;
			// If the autorun time is big than 60, run start.
			if ( 60 <= m_nAutorunTime )
			{
				KillTimer( TimerID::AutoStart );
				SetDlgItemText( IDC_STATIC_AUTOSTART, TEXT(""));
				m_nIsStart = STATE_AUTOSTART;
				CString str;
				str.Format( TEXT("AutoStart check IP address, Check Interval is %d minute, now IP is :"),m_unInterval);
				str += m_strIP;
				m_strList.InsertString(0, str );
				UpdateData(TRUE);
				SetTimer( TimerID::Start, m_unInterval*60*1000, NULL );
				SetTimer( TimerID::RunTime, 1000, NULL);
				UpdateIPAddress();
			}
			else
			{
				CString str;
				str.Format(TEXT("Process will auto start in %d Second."),60-m_nAutorunTime);
				SetDlgItemText( IDC_STATIC_AUTOSTART, str );
			}
		}
		break;
	case TimerID::RunTime:
		{
			m_unSecond++;
			if ( 60 == m_unSecond )
			{
				m_unMinute++;
				m_unSecond=0;
			}
			if ( 60 == m_unMinute )
			{
				m_unHour++;
				m_unMinute=0;
			}
			CString strTime;
			strTime.Format( TEXT("Runtime %2d:%2d:%2d"),m_unHour,m_unMinute,m_unSecond);
			SetDlgItemText( IDC_STATIC_RUNTIME, strTime);
		}
		break;
	default:
		break;
	}
	
	CDialogEx::OnTimer(nIDEvent);
}


void CCheckIPAddressDlg::OnBnClickedButtonSelect()
{
	// TODO: Add your control notification handler code here
	CFileDialog flg(FALSE, TEXT("txt"),TEXT("127.0.0.1") );
	
	if( IDOK == flg.DoModal())
	{
		m_strPath = flg.GetFolderPath();
		if ( -1 == m_strPath.Find(TEXT("\\"),m_strPath.GetLength()-1))
		{
			m_strPath += TEXT("\\");
		}
		UpdateData(0);
	}
}


void CCheckIPAddressDlg::OnBnClickedCheckAutorun()
{
	// TODO: Add your control notification handler code here
	HKEY hKey = NULL;
	RegOpenKey( HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), &hKey );
	if ( BST_CHECKED == m_CheckBtn.GetCheck() )
	{
		TCHAR filename[MAX_PATH]={0};
		GetModuleFileName(NULL,filename,MAX_PATH);
		RegSetValueEx(hKey,TEXT("CheckIPAddress"),0,REG_SZ,(const unsigned char *)filename,_MAX_PATH);
		m_strList.InsertString( 0, TEXT("Process will autorun with system start."));
		RegCloseKey(hKey);
	}
	else
	{
		RegDeleteValue(hKey,TEXT("CheckIPAddress"));
		m_strList.InsertString( 0, TEXT("Process will not autorun with system start."));
		RegCloseKey(hKey);
	}
}


void CCheckIPAddressDlg::OnBnClickedCheckNochangemsg()
{
	// TODO: Add your control notification handler code here
	CButton* btn = (CButton*)GetDlgItem(IDC_CHECK_NOCHANGEMSG);
	if( BST_CHECKED == btn->GetCheck() )
	{
		m_bNotShowNoChangeMessage = true;
		theApp.WriteProfileInt(TEXT("CheckIPAddress"),TEXT("NotShowChangeMessage"),1);
	}
	else
	{
		m_bNotShowNoChangeMessage = false;
		theApp.WriteProfileInt(TEXT("CheckIPAddress"),TEXT("NotShowChangeMessage"),0);
	}
}


void CCheckIPAddressDlg::OnCancel()
{
	// TODO: Add your specialized code here and/or call the base class
	if ( m_nIsStart != STATE_END )
	{
		if( IDYES != MessageBox(TEXT("Process is running, exit?"),TEXT("Warning"),MB_YESNO) )
		{
			return;
		}
	}
	this->OnBnClickedEnd();
	this->SetNotifyIcon( emNotifyIcon::Delete );
	CDialogEx::OnCancel();
}


void CCheckIPAddressDlg::OnBnClickedButtonChecknow()
{
	// TODO: Add your control notification handler code here
	UpdateIPAddress();
}


void CCheckIPAddressDlg::OnBnClickedCheckSinglefile()
{
	// TODO: Add your control notification handler code here
	CButton* btn = (CButton*)GetDlgItem(IDC_CHECK_SINGLEFILE);
	if( BST_CHECKED == btn->GetCheck() )
	{
		m_bSingleFile = true;
		theApp.WriteProfileInt(TEXT("CheckIPAddress"),TEXT("SingleFile"),1);
	}
	else
	{
		m_bSingleFile = false;
		theApp.WriteProfileInt(TEXT("CheckIPAddress"),TEXT("SingleFile"),0);
	}
}


void CCheckIPAddressDlg::SetNotifyIcon( emNotifyIcon emNotifyType )
{
	NOTIFYICONDATA nd;
	
	nd.cbSize = sizeof(NOTIFYICONDATA);
	nd.hWnd = m_hWnd;
	nd.uID = IDR_MAINFRAME;
	nd.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
	nd.uCallbackMessage = MYWM_NOTIFYICON;
	nd.hIcon = m_hIcon;
	_tcscpy_s(nd.szTip,ARRAYSIZE(nd.szTip), TEXT("CheckIPAddress"));

	switch ( emNotifyType )
	{
	case emNotifyIcon::Create:
		{
			Shell_NotifyIcon(NIM_ADD, &nd);
		}
		break;
	case emNotifyIcon::Delete:
		{
			Shell_NotifyIcon(NIM_DELETE, &nd);
		}
		break;
	default:
		break;
	}
	
}


LRESULT CCheckIPAddressDlg::OnNotifyIcon(WPARAM wParam, LPARAM lParam)
{
	switch ( lParam )
	{
	case WM_LBUTTONDBLCLK:
		{
			UINT MODE;
			MODE = IsWindowVisible() ? SW_HIDE : SW_SHOW;
			ShowWindow(MODE);
			break;
		}
	case WM_LBUTTONDOWN:
	case WM_RBUTTONDOWN:
		{
			CMenu menu,*pSubMenu; 
			CPoint point;
			menu.LoadMenu(IDR_NOTIFYMENU); 
			pSubMenu = menu.GetSubMenu(0); 
			GetCursorPos(&point); 
			pSubMenu->TrackPopupMenu(TPM_LEFTALIGN,point.x,point.y,this);
			break;
		}
	default:
		break;
	}
	
	return ERROR_SUCCESS;
}

void CCheckIPAddressDlg::OnNotifyShow()
{
	// TODO: Add your command handler code here
	UINT MODE;
	MODE = IsWindowVisible() ? SW_HIDE : SW_SHOW;
	ShowWindow(MODE);
}


void CCheckIPAddressDlg::OnNotifyRun()
{
	// TODO: Add your command handler code here
	if( m_nIsStart == STATE_END )
	{
		OnBnClickedStart();
	}
	else
	{
		OnBnClickedEnd();
	}
}

void CCheckIPAddressDlg::OnNotifyExit()
{
	// TODO: Add your command handler code here
	OnCancel();
}


BOOL CCheckIPAddressDlg::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Add your specialized code here and/or call the base class
	cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
	cs.style &= ~WS_MAXIMIZEBOX;
	cs.style &= ~WS_THICKFRAME;
	cs.lpszClass = AfxRegisterWndClass(0);
	return CDialogEx::PreCreateWindow(cs);
}
